
package org.jeecg.modules.system.util;

import com.alibaba.fastjson.JSONObject;
import com.jeecg.qywx.api.core.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Slf4j
public class WxUtils {

    private static String accessToken = "accessToken";

    public static String appSercet = "8ab1c49fd5ac38b669f5494ca476c41e";


    @Autowired
    private RedisUtil redisUtil;
    private static String appid = "wx863c29ee689022e8";


    public WxUtils() {
        super();
    }

    public String initAccessToken() {
        Object accessToken1 = null;
        accessToken1 = redisUtil.get(appid);
        if (accessToken1 == null) {
            JSONObject jsonObject = null;
            jsonObject = this.actionAccessToken(appid, appSercet);
            redisUtil.set(appid, jsonObject.getString("access_token"));
            //缓存有效期为2个小时
            redisUtil.expire(appid, 7000);
            return jsonObject.getString("access_token");
        } else {
            return accessToken1.toString();
        }
    }


    JSONObject actionAccessToken(String appid, String appSercet) {
        String url = null;
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSercet;
        JSONObject jsonObject = HttpUtil.sendGet(url);
        return jsonObject;
    }

    //根据code获取用户手机号
    public String getPhoneByCode(String code, String access_token) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token= " + access_token;
        JSONObject parms = new JSONObject();
        parms.put("code", code);
        log.info("获取手机号请求入参:" + parms.toJSONString());
        JSONObject jsonObject = HttpUtil.sendPost(url, parms.toString());
        if(jsonObject.getInteger("errcode")!=0){
            throw new RuntimeException("获取手机号失败:"+jsonObject.toJSONString());
        }else{
            String phone = jsonObject.getJSONObject("phone_info").getString("purePhoneNumber");
            log.info("获取手机号返回结果:"+jsonObject.toJSONString());
            return phone;
        }

    }


}
